<template>
  <div class="company-container">
    <!-- Backdrop Overlay -->
    <transition name="fade">
      <div v-if="expandedCompanyId" class="page-overlay" @click="toggleOrganizationView(expandedCompanyId)"></div>
    </transition>

    <!-- 搜索和添加区域 -->
    <div class="header-container">
      <div class="search-toggle-area">
        <el-button class="search-toggle-button" @click="toggleSearchBar">
          <el-icon><Search /></el-icon>
        </el-button>
        <el-form :inline="true" :model="searchForm" class="search-form" :class="{'is-hidden': !showSearchBar}">
          <el-form-item label="公司名称">
            <el-input v-model="searchForm.companyName" placeholder="请输入公司名称" clearable />
          </el-form-item>
          <el-form-item label="联系电话">
            <el-input v-model="searchForm.contactPhone" placeholder="请输入联系电话" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="add-button">
        <el-button type="primary" @click="handleAdd" class="add-company-btn"><el-icon><Plus /></el-icon>添加公司</el-button>
      </div>
    </div>

    <!-- 卡片区域 -->
    <div v-loading="loading" class="card-container">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="item in tableData" :key="item.company_id" class="card-item" :class="{'is-active-item': expandedCompanyId === item.company_id}">
          <!-- 公司卡片 -->
          <el-card shadow="hover" class="company-card" :class="{'is-expanded': expandedCompanyId === item.company_id}" :style="{'--company-border-color': getCardBorderColor(item.company_type)}" body-style="{ padding: '0px 18px' }">
            <template #header>
              <div class="card-header" @click="toggleOrganizationView(item.company_id)">
                <h3 class="company-name" :title="item.company_name">{{ item.company_name }}</h3>
                <el-icon class="expand-icon" :class="{'is-active': expandedCompanyId === item.company_id}"><ArrowDownBold /></el-icon>
              </div>
            </template>
            <!-- 删除按钮 -->
            <div class="delete-button" @click.stop>
              <el-popconfirm
                title="确认删除该公司信息吗？"
                confirm-button-text="确定"
                cancel-button-text="取消"
                @confirm="handleDelete(item)"
              >
                <template #reference>
                  <el-button type="danger" link><el-icon><Delete /></el-icon></el-button>
                </template>
              </el-popconfirm>
            </div>
            <!-- 公司信息 -->
            <div class="card-content" @click="toggleOrganizationView(item.company_id)">
              <p><i class="el-icon-office-building"></i> <span class="label">信用代码:</span> {{ item.credit_code }}</p>
              <p><i class="el-icon-phone"></i> <span class="label">联系电话:</span> {{ item.contact_phone }}</p>
              <p><i class="el-icon-date"></i> <span class="label">入驻日期:</span> {{ item.entry_date }}</p>
            </div>
            <!-- 卡片底部 -->
            <div class="card-footer">
              <el-tag size="small" effect="dark" :type="getCompanyTypeTag(item.company_type)">{{ item.company_type }}</el-tag>
              <div class="footer-actions">
                <el-button type="primary" link @click.stop="handleEdit(item)">编辑</el-button>
                <el-button type="primary" link @click.stop="handleView(item)">详情</el-button>
              </div>
            </div>
          </el-card>

          <!-- 组织架构展开区域 -->
          <div v-if="expandedCompanyId === item.company_id" class="organization-section">
            <div v-if="organizationLoading" class="organization-loading-container">
              <el-icon class="is-loading" :size="26"><Loading /></el-icon>
              <span>正在加载...</span>
            </div>
            <div v-else class="organization-container">
              <div v-if="departmentTree.length > 0" class="department-grid" :style="gridStyle">
                <div v-for="dept in departmentTree" :key="dept.departmentName" class="department-column">
                  <div class="department-header" @click="toggleDepartmentCollapse(dept.departmentName)">
                    <span class="department-title">{{ dept.departmentName }}</span>
                    <div class="department-header-right">
                      <el-tag size="small" type="info" class="department-count-tag">{{ dept.employees.length }} 人</el-tag>
                      <el-icon class="department-expand-icon" :class="{'is-active': activeDepartmentNames.includes(dept.departmentName)}"><ArrowDownBold /></el-icon>
                    </div>
                  </div>
                  <el-collapse-transition>
                    <div v-show="activeDepartmentNames.includes(dept.departmentName)">
                      <div class="employee-list-container">
                        <el-card shadow="hover" v-for="emp in dept.employees" :key="emp.id" class="employee-card" :class="{'manager-card': emp.isManager}">
                          <div class="employee-card-content">
                            <div class="employee-info">
                              <span class="employee-name">{{ emp.name }}</span>
                              <span class="employee-position">{{ emp.position }}</span>
                            </div>
                            <el-tag size="small" effect="dark" :type="emp.status === 1 ? 'success' : 'danger'">
                              {{ emp.status === 1 ? '在职' : '离职' }}
                            </el-tag>
                          </div>
                        </el-card>
                      </div>
                    </div>
                  </el-collapse-transition>
                </div>
              </div>
              <el-empty v-if="departmentTree.length === 0 && !organizationLoading" description="该公司暂无员工数据"></el-empty>
            </div>
          </div>
        </el-col>
      </el-row>
      
      <!-- 空数据提示 -->
      <el-empty v-if="tableData.length === 0 && !loading" description="暂无公司数据" class="empty-data-placeholder"></el-empty>
    </div>
    
    <!-- 分页区域 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[12, 24, 36, 48]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <el-form
        ref="companyFormRef"
        :model="companyForm"
        :rules="companyFormRules"
        label-width="140px"
      >
        <el-form-item label="公司名称" prop="company_name">
          <el-input v-model="companyForm.company_name" placeholder="请输入公司名称" />
        </el-form-item>
        <el-form-item label="公司类型" prop="company_type">
          <el-select v-model="companyForm.company_type" placeholder="请选择公司类型" style="width: 100%">
            <el-option label="物业公司" value="物业公司" />
            <el-option label="科技企业" value="科技企业" />
            <el-option label="服务企业" value="服务企业" />
            <el-option label="制造企业" value="制造企业" />
            <el-option label="贸易企业" value="贸易企业" />
            <el-option label="金融企业" value="金融企业" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="统一社会信用代码" prop="credit_code">
          <el-input v-model="companyForm.credit_code" placeholder="请输入统一社会信用代码" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contact_phone">
          <el-input v-model="companyForm.contact_phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="入驻日期" prop="entry_date">
          <el-date-picker 
            v-model="companyForm.entry_date" 
            type="date" 
            placeholder="请选择入驻日期"
            style="width: 100%"
            value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="companyForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入公司描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog 
      title="公司详情" 
      v-model="viewDialogVisible" 
      width="700px"
      destroy-on-close
      custom-class="company-detail-dialog"
    >
      <div class="company-detail-container">
        <div class="company-detail-header">
          <div class="company-detail-title">
            <h2>{{ companyDetail.company_name }}</h2>
            <el-tag size="medium" effect="dark" :type="getCompanyTypeTag(companyDetail.company_type)">{{ companyDetail.company_type }}</el-tag>
          </div>
          <div class="company-detail-meta">
            <span>创建于 {{ formatDate(companyDetail.created_at) }}</span>
            <span>最后更新 {{ formatDate(companyDetail.updated_at) }}</span>
          </div>
        </div>
        
        <el-divider></el-divider>
        
        <div class="company-detail-content">
          <div class="detail-item">
            <div class="detail-label">统一社会信用代码</div>
            <div class="detail-value">{{ companyDetail.credit_code }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">联系电话</div>
            <div class="detail-value">{{ companyDetail.contact_phone }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">入驻日期</div>
            <div class="detail-value">{{ companyDetail.entry_date }}</div>
          </div>
          <div class="detail-item full-width">
            <div class="detail-label">公司描述</div>
            <div class="detail-value description">{{ companyDetail.description || '暂无描述' }}</div>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="viewDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleEdit(companyDetail)">编辑</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, ArrowDownBold, Delete, Loading } from '@element-plus/icons-vue' // Import Search, Plus, ArrowDownBold, Delete, Loading icon
import {
  getCompanyList,
  getCompanyById,
  createCompany,
  updateCompany,
  deleteCompany,
  getEmployeeList,
  getParkEmployeeList
} from '@/api/personnel.js'
import { useRouter } from 'vue-router'

export default {
  name: 'CompanyList',
  components: {
    Search, // Register Search icon component
    Plus,    // Register Plus icon component
    ArrowDownBold,
    Delete,
    Loading
  },
  setup() {
    const router = useRouter()
    // 表格数据相关
    const loading = ref(false)
    const tableData = ref([])
    
    // 新增：组织架构相关状态
    const expandedCompanyId = ref(null)
    const organizationLoading = ref(false)
    const departmentTree = ref([])
    const activeDepartmentNames = ref([]) // 控制部门折叠面板
    const gridStyle = ref({}) // 用于控制网格布局样式

    // 搜索栏显示状态
    const showSearchBar = ref(false)

    // 分页相关
    const currentPage = ref(1)
    const pageSize = ref(12) // 修改默认每页显示数量为12个
    const total = ref(0)
    
    // 搜索表单
    const searchForm = reactive({
      companyName: '',
      contactPhone: ''
    })
    
    // 公司表单
    const companyFormRef = ref(null)
    const companyForm = reactive({
      company_id: null,
      company_type: '',
      company_name: '',
      credit_code: '',
      contact_phone: '',
      entry_date: '',
      description: ''
    })
    
    // 表单验证规则
    const companyFormRules = {
      company_name: [
        { required: true, message: '请输入公司名称', trigger: 'blur' },
        { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
      ],
      company_type: [
        { required: true, message: '请选择公司类型', trigger: 'change' }
      ],
      credit_code: [
        { required: true, message: '请输入统一社会信用代码', trigger: 'blur' },
        { pattern: /^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$/, message: '请输入正确的统一社会信用代码', trigger: 'blur' }
      ],
      contact_phone: [
        { required: true, message: '请输入联系电话', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
      ],
      entry_date: [
        { required: true, message: '请选择入驻日期', trigger: 'change' }
      ]
    }
    
    // 对话框相关
    const dialogVisible = ref(false)
    const viewDialogVisible = ref(false)
    const dialogType = ref('add') // 'add' 或 'edit'
    const companyDetail = ref({})
    
    const dialogTitle = computed(() => {
      return dialogType.value === 'add' ? '添加公司' : '编辑公司'
    })
    
    // 获取公司类型对应的标签类型和边框颜色
    const getCompanyTypeTag = (type) => {
      switch(type) {
        case '物业公司': return 'primary';
        case '科技企业': return 'success';
        case '服务企业': return 'warning';
        case '制造企业': return 'danger';
        case '贸易企业': return 'info';
        case '金融企业': return '';
        case '其他': return 'info';
        default: return 'info';
      }
    }
    
    const getCardBorderColor = (type) => {
      switch(type) {
        case '物业公司': return '#409EFF';
        case '科技企业': return '#67C23A';
        case '服务企业': return '#E6A23C';
        case '制造企业': return '#F56C6C';
        case '贸易企业': return '#909399';
        case '金融企业': return '#c772e0';
        default: return '#b1b3b8';
      }
    }
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleDateString()
    }
    
    // 获取公司列表数据
    const fetchCompanyList = async () => {
      loading.value = true
      try {
        const params = {
          page: currentPage.value,
          pageSize: pageSize.value,
          companyName: searchForm.companyName,
          contactPhone: searchForm.contactPhone,
          excludeCompanyType: '物业公司'
        }
        const res = await getCompanyList(params)
        if (res.data && res.data.data && res.data.data.list) {
          tableData.value = res.data.data.list
          total.value = res.data.data.total
        } else {
          ElMessage.warning('获取公司列表数据格式不正确')
          tableData.value = []
          total.value = 0
        }
      } catch (error) {
        console.error('获取公司列表失败:', error)
        ElMessage.error('获取公司列表失败')
        tableData.value = []
        total.value = 0
      } finally {
        loading.value = false
      }
    }
    
    // 新增：获取公司员工数据并构建部门树
    const fetchCompanyEmployees = async (companyId) => {
      organizationLoading.value = true
      departmentTree.value = []
      try {
        // 根据公司ID从列表数据中找到对应的公司对象
        const company = tableData.value.find(c => c.company_id === companyId)
        if (!company) {
          ElMessage.error('未找到对应的公司信息')
          organizationLoading.value = false
          return
        }

        const params = {
          page: 1,
          pageSize: 1000, // 获取所有员工
        }
        
        let res;
        // 判断公司类型，如果是物业公司，则调用获取园区员工的接口
        if (company.company_type === '物业公司') {
          res = await getParkEmployeeList(params)
        } else {
          // 否则，调用获取企业员工的接口
          params.companyId = companyId
          res = await getEmployeeList(params)
        }
        
        if (res.data && res.data.data && res.data.data.list) {
          const employees = res.data.data.list
          const groupedByDept = employees.reduce((acc, employee) => {
            const dept = employee.department || '未分配部门'
            if (!acc[dept]) {
              acc[dept] = []
            }
            acc[dept].push(employee)
            return acc
          }, {})

          departmentTree.value = Object.entries(groupedByDept).map(([deptName, employees]) => ({
            departmentName: deptName,
            employees: employees.map(e => ({ ...e, isManager: e.position && e.position.includes('经理') }))
              .sort((a, b) => (b.isManager || 0) - (a.isManager || 0))
          }))
          // 默认收起所有部门
          activeDepartmentNames.value = [] // 初始化为空数组，表示所有部门都是收起状态
          
          // 根据部门数量计算网格布局
          calculateGridLayout()
        } else {
          ElMessage.warning('获取员工数据格式不正确')
        }
      } catch (error) {
        console.error('获取公司员工列表失败:', error)
        ElMessage.error('获取公司员工列表失败')
      } finally {
        organizationLoading.value = false
      }
    }

    // 计算网格布局样式
    const calculateGridLayout = () => {
      // 根据部门数量和屏幕宽度计算列数
      const deptCount = departmentTree.value.length
      let columns = Math.min(deptCount, 3) // 最多3列，避免列太窄
      
      if (deptCount > 0) {
        gridStyle.value = {
          'grid-template-columns': `repeat(${columns}, 1fr)`,
          'grid-gap': '20px'
        }
      }
    }
    
    // 新增：切换组织架构显示
    const toggleOrganizationView = (companyId) => {
      if (expandedCompanyId.value === companyId) {
        expandedCompanyId.value = null
        departmentTree.value = [] // 收起时清空数据
      } else {
        expandedCompanyId.value = companyId
        fetchCompanyEmployees(companyId)
      }
    }
    
    // 新增：切换单个部门的折叠状态
    const toggleDepartmentCollapse = (departmentName) => {
      const index = activeDepartmentNames.value.indexOf(departmentName);
      if (index > -1) {
        activeDepartmentNames.value.splice(index, 1);
      } else {
        activeDepartmentNames.value.push(departmentName);
      }
    };
    
    // 搜索
    const handleSearch = () => {
      currentPage.value = 1
      fetchCompanyList()
    }
    
    // 重置搜索
    const resetSearch = () => {
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = ''
      })
      currentPage.value = 1
      fetchCompanyList()
    }
    
    // 分页相关方法
    const handleSizeChange = (val) => {
      pageSize.value = val
      fetchCompanyList()
    }
    
    const handleCurrentChange = (val) => {
      currentPage.value = val
      fetchCompanyList()
    }
    
    // 添加公司
    const handleAdd = () => {
      dialogType.value = 'add'
      resetCompanyForm()
      dialogVisible.value = true
    }
    
    // 编辑公司
    const handleEdit = (row) => {
      dialogType.value = 'edit'
      resetCompanyForm()
      // 如果是从详情页点击编辑，直接使用已有数据
      if (viewDialogVisible.value) {
        Object.assign(companyForm, {
          company_id: row.company_id,
          company_name: row.company_name,
          company_type: row.company_type,
          credit_code: row.credit_code,
          contact_phone: row.contact_phone,
          entry_date: row.entry_date,
          description: row.description
        });
        viewDialogVisible.value = false; // 关闭详情弹窗
        dialogVisible.value = true;      // 打开编辑弹窗
        return;
      }
      
      // 直接从列表的卡片中获取数据
      Object.assign(companyForm, {
        company_id: row.company_id,
        company_name: row.company_name,
        company_type: row.company_type,
        credit_code: row.credit_code,
        contact_phone: row.contact_phone,
        entry_date: row.entry_date,
        description: row.description
      });
      dialogVisible.value = true
    }
    
    // 查看公司详情
    const handleView = async (row) => {
      try {
        const res = await getCompanyById(row.company_id);
        if (res.data && res.data.data) {
          companyDetail.value = res.data.data
        } else {
          ElMessage.error('获取公司详情数据格式错误');
          return;
        }
        viewDialogVisible.value = true
      } catch (error) {
        console.error('获取公司详情失败', error)
        ElMessage.error('获取公司详情失败');
      }
    };
    
    // 查看员工按钮点击事件
    const handleViewEmployees = (companyId) => {
      router.push({ name: 'CompanyEmployeeList', query: { companyId } })
    }

    // 删除公司
    const handleDelete = async (row) => {
      try {
        await deleteCompany(row.company_id)
        ElMessage.success('删除成功')
        if (tableData.value.length === 1 && currentPage.value > 1) { // 调整分页逻辑
          currentPage.value--
        }
        fetchCompanyList()
      } catch (error) {
        console.error('删除公司失败', error)
        ElMessage.error('删除公司失败')
      }
    }
    
    // 重置表单
    const resetCompanyForm = () => {
      if (companyFormRef.value) {
        companyFormRef.value.resetFields()
      }
      Object.assign(companyForm, {
        company_id: null,
        company_type: '',
        company_name: '',
        credit_code: '',
        contact_phone: '',
        entry_date: '',
        description: ''
      })
    }
    
    // 提交表单
    const submitForm = () => {
      companyFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            if (dialogType.value === 'add') {
              await createCompany(companyForm)
              ElMessage.success('添加成功')
            } else {
              await updateCompany(companyForm.company_id, companyForm)
              ElMessage.success('更新成功')
            }
            dialogVisible.value = false
            fetchCompanyList()
          } catch (error) {
            console.error('保存公司信息失败', error)
            ElMessage.error('保存公司信息失败')
          }
        }
      })
    }
    
    // 切换搜索栏显示状态
    const toggleSearchBar = () => {
      showSearchBar.value = !showSearchBar.value;
    }
    
    onMounted(() => {
      fetchCompanyList()
    })
    
    return {
      loading,
      tableData,
      currentPage,
      pageSize,
      total,
      searchForm,
      companyForm,
      companyFormRef,
      companyFormRules,
      dialogVisible,
      viewDialogVisible,
      dialogType,
      dialogTitle,
      companyDetail,
      showSearchBar,
      handleSearch,
      resetSearch,
      handleSizeChange,
      handleCurrentChange,
      handleAdd,
      handleEdit,
      handleView,
      handleDelete,
      submitForm,
      toggleSearchBar,
      formatDate,
      getCompanyTypeTag,
      getCardBorderColor,
      handleViewEmployees,

      // 新增返回
      expandedCompanyId,
      organizationLoading,
      departmentTree,
      toggleOrganizationView,
      activeDepartmentNames,
      toggleDepartmentCollapse,
      gridStyle
    }
  }
}
</script>

<style scoped>
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.org-fade-enter-active,
.org-fade-leave-active {
  transition: opacity 0.2s ease;
}
.org-fade-enter-from,
.org-fade-leave-to {
  opacity: 0;
}

/* 基础布局 */
.company-container {
  padding: 20px;
  background-color: #f8f9fa; /* 轻微的页面背景色 */
  min-height: calc(100vh - 80px); /* 确保页面有足够高度 */
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center; /* Adjusted to center for better vertical alignment with the search toggle and add button */
  margin-bottom: 15px; /* Reduced margin-bottom to bring cards closer */
  padding: 10px 20px; /* Reduced top padding to move the search row up */
  background-color: transparent; /* Make background transparent */
  box-shadow: none; /* Remove shadow */
  border-radius: 10px;
  position: relative; /* For absolute positioning of toggle button */
}

.search-toggle-area {
  display: flex;
  flex-direction: row; /* Changed to row for horizontal layout */
  align-items: center; /* Center items vertically */
  flex-grow: 1; /* Allow it to take available space */
}

.search-toggle-button {
  font-size: 20px; /* Larger icon */
  color: #606266; /* Subtle grey color */
  align-self: center; /* Align button to the center of the row */
  margin-right: 15px; /* Space between button and search form */
  transition: all 0.2s; /* Changed to all for full transition */
  cursor: pointer; /* Explicitly set cursor */
  width: 36px; /* Fixed width */
  height: 36px; /* Fixed height */
  display: flex; /* Use flex to center icon */
  justify-content: center; /* Center icon */
  align-items: center; /* Center icon */
  border-radius: 50%; /* Make it round */
  background-color: rgba(0, 0, 0, 0.03); /* Subtle background */
  border: 1px solid rgba(0, 0, 0, 0.05); /* Subtle border */
  z-index: 10; /* Ensure it's on top */
  margin-bottom: 0; /* Adjusted margin-bottom */
}

.search-toggle-button:hover {
  color: #409eff; /* Hover effect */
  background-color: rgba(64, 158, 255, 0.1); /* Hover effect */
  border-color: rgba(64, 158, 255, 0.2); /* Hover border */
}

.search-form {
  /* Use max-width for horizontal animation */
  max-width: 1000px; /* Increased max width to ensure content is always visible when expanded */
  width: auto; /* Allow width to be determined by content */
  overflow: hidden;
  transition: max-width 0.4s ease-in-out, opacity 0.4s ease-in-out, background-color 0.4s ease-in-out, box-shadow 0.4s ease-in-out, padding 0.4s ease-in-out, margin-left 0.4s ease-in-out, height 0.4s ease-in-out, min-height 0.4s ease-in-out; /* Smooth transition for all relevant properties */
  opacity: 1;
  background-color: transparent; /* Set background to transparent */
  border-radius: 8px; /* Slightly smaller radius for search form itself */
  padding: 0 20px; /* Adjusted padding to 0 for vertical, 20px for horizontal */
  box-shadow: none; /* Remove shadow */
  pointer-events: auto; /* Allow interaction when visible */
  margin-left: 15px; /* Add margin when visible */
  white-space: nowrap; /* Prevent content from wrapping */
  height: 35px; /* Fixed height for the search form */
  min-height: 35px; /* Fixed min-height for the search form */
}

.search-form.is-hidden {
  max-width: 0; /* Hidden state */
  opacity: 0;
  padding: 0; /* Remove padding when hidden */
  margin-left: 0; /* Remove margin when hidden */
  height: 0; /* Ensure vertical collapse */
  min-height: 0; /* Ensure vertical collapse */
  background-color: transparent; /* Transparent background when hidden */
  box-shadow: none; /* No shadow when hidden */
  pointer-events: none; /* Crucial for preventing interaction when hidden */
}

/* 调整搜索表单项的底部外边距，使其更紧凑 */
:deep(.search-form .el-form-item) {
  margin-bottom: 0; /* Removed bottom margin for horizontal alignment */
  margin-right: 15px; /* Added right margin for spacing between items */
  display: inline-flex; /* Ensure items are inline-flex for horizontal layout */
  align-items: center; /* Vertically align content within form item */
}

/* 确保表单项内部的label和input/select水平对齐 */
:deep(.search-form .el-form-item__label) {
  padding-right: 8px; /* Add some space between label and input */
}

.add-button {
  /* Positioned to the right of the header-container */
  margin-left: 20px; /* Maintain some distance from search */
  flex-shrink: 0; /* Prevent it from shrinking */
  align-self: center; /* Align to center with search toggle and form */
}

/* Custom style for Add Company button to center text and icon */
:deep(.add-company-btn) {
  display: inline-flex; /* Ensure it behaves as a flex container */
  align-items: center; /* Vertically align content */
  justify-content: center; /* Horizontally align content */
  gap: 5px; /* Add spacing between icon and text */
}

/* 卡片区域 */
.card-container {
  min-height: 400px;
}

.card-item {
  margin-bottom: 25px;
  /* Add transition for z-index or other properties if needed */
  transition: z-index 0s 0.3s;
}

.card-item.is-active-item {
  position: relative; /* This is crucial for the child's absolute positioning */
  z-index: 101; /* Bring the active card item above the overlay */
  transition: z-index 0s;
}

.company-card {
  cursor: pointer;
  transition: all 0.3s ease;
  border-top-width: 4px;
  border-top-style: solid;
  border-color: transparent; /* Fallback */
  border-left-color: var(--company-border-color);
  border-left-width: 4px;
}
.company-card.is-expanded {
  box-shadow: 0 8px 16px rgba(0,0,0,0.1);
  transform: translateY(-2px);
  border-color: var(--company-border-color);
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.expand-icon {
  transition: transform 0.3s ease;
}
.expand-icon.is-active {
  transform: rotate(180deg);
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 10px;
}
.footer-actions {
  display: flex;
  gap: 8px;
}

/* 组织架构区域样式 */
.organization-section {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 80%;
  max-width: 1200px;
  min-width: 600px;
  max-height: 80vh;
  padding: 20px;
  background-color: #ffffff;
  border: 1px solid #e0e6ed;
  border-radius: 8px;
  box-shadow: 0 6px 24px rgba(0,0,0,0.15);
  z-index: 102; /* Above the card and overlay */
  overflow: hidden;
  display: flex;
  flex-direction: column;
}
.organization-loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100px;
  gap: 10px;
  color: #606266;
  font-size: 14px;
}
.organization-container {
  min-height: 100px;
  max-height: calc(80vh - 40px); /* 减去padding */
  overflow-y: auto;
}
.department-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}
.department-column {
  background-color: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
  display: flex;
  flex-direction: column;
  height: fit-content;
}
.department-header {
  padding: 10px 15px;
  border-bottom: 1px solid #e9ecef;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
  transition: background-color 0.2s;
}
.department-header:hover {
  background-color: #f1f3f5;
}
.department-header-right {
  display: flex;
  align-items: center;
  gap: 8px;
}
.department-expand-icon {
  transition: transform 0.3s ease;
}
.department-expand-icon.is-active {
  transform: rotate(180deg);
}
.department-title {
  font-size: 15px;
  font-weight: 600;
}
.department-count-tag {
  margin-left: 10px;
}
.employee-list-container {
  padding: 10px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.employee-card-item {
  /* This class is no longer used for direct styling */
}
.employee-card {
  border-radius: 6px;
  background: #fff;
  border: 1px solid #eef2f8;
  transition: all 0.2s ease-in-out;
}
.employee-card:hover {
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
  transform: translateY(-1px);
}
.manager-card {
  background-color: #fff9f2;
  border-color: #e6a23c;
}
:deep(.employee-card .el-card__body) {
  padding: 10px 15px;
}
.employee-card-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.employee-info {
  display: flex;
  flex-direction: column;
}
.employee-name {
  font-weight: 500;
  font-size: 14px;
}
.employee-position {
  font-size: 12px;
  color: #909399;
}

/* 删除按钮样式 */
.delete-button {
  position: absolute;
  top: 15px;
  right: 45px; /* Adjust to not overlap with the expand icon */
  opacity: 0;
  transition: opacity 0.3s ease;
}
.company-card:hover .delete-button {
  opacity: 1;
}
.delete-icon span {
  margin-left: 4px;
}

/* 分页 */
.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: flex-end;
  padding: 15px 20px;
  background-color: #f9fbfd; /* Changed to a softer, off-white background */
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03); /* Adjusted to a softer, more diffused shadow */
}

.empty-data-placeholder {
  margin-top: 50px;
}

/* 公司详情样式 */
.company-detail-dialog .el-dialog__header {
  padding-bottom: 10px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.08); /* 调整为更淡的边框 */
}

.company-detail-dialog .el-dialog__body {
  padding: 25px 30px;
}

.company-detail-header {
  margin-bottom: 25px;
  text-align: center;
}

.company-detail-title {
  display: flex;
  align-items: center;
  justify-content: center; /* 标题居中 */
  gap: 15px;
  margin-bottom: 12px;
}

.company-detail-title h2 {
  margin: 0;
  font-size: 26px; /* 减小字体大小 */
  color: #303133;
  font-weight: 700;
}

.company-detail-meta {
  display: flex;
  justify-content: center; /* 元信息居中 */
  gap: 25px;
  color: #909399;
  font-size: 13px; /* 略微缩小 */
}

.el-divider {
  margin: 20px 0; /* 调整间距 */
}

.company-detail-content {
  display: flex;
  flex-wrap: wrap;
  gap: 25px 20px; /* 调整间距 */
}

.detail-item {
  width: calc(50% - 10px);
  margin-bottom: 0;
  padding: 10px 0;
  border-bottom: 1px dashed #e4e7ed; /* 虚线分隔 */
}

.detail-item.full-width {
  width: 100%;
  border-bottom: none;
  padding-bottom: 0;
}

.detail-label {
  font-size: 13px; /* 略微缩小 */
  color: #909399;
  margin-bottom: 6px;
}

.detail-value {
  font-size: 16px;
  color: #303133;
  font-weight: 500;
}

.detail-value.description {
  white-space: pre-line;
  line-height: 1.7;
  padding: 15px;
  background-color: #fcfdfe; /* 更浅的背景色 */
  border-radius: 8px;
  min-height: 100px; /* 略微增大 */
  border: 1px solid #e9eff5;
  box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.05);
}

/* 自定义对话框样式 */
:deep(.company-detail-dialog .el-dialog__body) {
  padding-top: 20px;
}

/* 搜索框el-input优化 */
:deep(.el-input__inner) {
  border-color: #e0e5ed !important; /* Default border to very light grey */
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  border-radius: 6px; /* Added border-radius */
}

:deep(.el-input__inner:focus) {
  border-color: rgba(64, 158, 255, 0.4) !important; /* Soft blue on focus */
}

:deep(.el-input__inner::placeholder) {
  color: #aebccf; /* Lighter placeholder text */
}

/* 按钮el-button优化 */
/* Primary Button (查询, 添加公司) */
:deep(.el-button--primary) {
  background-color: rgba(64, 158, 255, 0.1) !important; /* Very light blue background with transparency */
  color: #606266 !important; /* Soft dark grey text for better contrast */
  border-color: rgba(64, 158, 255, 0.2) !important; /* Slightly more visible but soft blue border */
  transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  border-radius: 6px; /* Added border-radius */
}

:deep(.el-button--primary:hover) {
  background-color: rgba(64, 158, 255, 0.15) !important; /* Slightly darker hover background */
  border-color: rgba(64, 158, 255, 0.3) !important; /* Slightly darker hover border */
}

/* Default Button (重置) */
:deep(.el-button--default) {
  background-color: #ffffff !important; /* Keep white background */
  color: #606266 !important; /* Soft dark grey text */
  border-color: #dcdfe6 !important; /* Light grey border */
  transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  border-radius: 6px; /* Added border-radius */
}

:deep(.el-button--default:hover) {
  background-color: #f7f9fa !important; /* Slightly grey hover background */
  border-color: #c8d3dd !important; /* Slightly darker hover border */
}

/* Backdrop and Overlay Logic */
.page-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(2px);
  z-index: 100;
}
</style>

